#! /usr/bin/env ruby

# frozen_string_literal: true

LKP_SRC ||= ENV['LKP_SRC'] || File.dirname(File.dirname(File.dirname(File.realpath($PROGRAM_NAME))))

require "#{LKP_SRC}/lib/load_file"
require "#{LKP_SRC}/lib/scheduler_client"

def die(msg)
  puts msg
  exit
end

def _alter_field(default_field, field_list)
end

def merge_fields(fields, field_specs)
  field_specs.each do |field_spec|
    if field_spec.start_with?('-')
      field_spec.sub!(/^-/, '').split(',').each do |f| fields.delete(f) end
    elsif field_spec.start_with?('+')
      fields.concat field_spec.sub!(/^\+/, '').split(',')
    else
      fields = field_spec.split(',')
    end
  end
  fields
end

def get_where_list(argv)
  where_list = []
  unless argv.empty?
    argv.each do |a|
      k, v = a.split('=')

      if v == '+'
        where_list << "#{k} IS NOT NULL"
        next
      end
      if v == '-'
        where_list << "#{k} IS NULL"
        next
      end

      where_list << "#{k}=\'#{v}\'"
    end
  end
  where_list
end

def read_cci_credentials
  data_hash = {}
  hash = load_my_config
  data_hash['cci_credentials'] = {
    'my_account' => hash['my_account'],
    'my_token' => hash['my_token']
  }

  data_hash['DATA_API_HOST'] ||= hash['DATA_API_HOST'] || hash['SCHED_HOST']
  data_hash['DATA_API_PORT'] ||= hash['DATA_API_PORT'] || '20003'

  raise 'Please configure DATA_API_HOST' if data_hash['DATA_API_HOST'].nil?

  return data_hash
end

def es_opendistro_query(data_hash)
  dataapi_client = DataApiClient.new(data_hash['DATA_API_HOST'], data_hash['DATA_API_PORT'])
  response = dataapi_client.es_opendistro_sql(data_hash.to_json)
  response = JSON.parse(response)
  die(response['error_msg']) if response['error_msg']
  response
end
